package net.zoneland.knowledge.service.impl.search;

import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import net.zoneland.knowledge.model.EsQuestion;
import net.zoneland.knowledge.service.EsService;
import net.zoneland.knowledge.service.SubjectLevelService;

/**
 * 点左侧R慧办链接显示所有.
 *
 * @author: bcc
 * 2021/5/26
 */
@Service("searchOperationImplQueryShowAll")
public class SearchOperationImplQueryShowAll extends AbstractSearchOperation {

    /**
     * logger.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(SearchOperationImplQueryShowAll.class);

    @Autowired
    private EsService esService;
    
    @Value("${search.querySubjectFormConfig:true}")
    private boolean querySubjectFormConfig;
    
    @Autowired
    private SubjectLevelService subjectLevelService;
    
    @Override
    public boolean needRun(final SearchDto searchDto) {
        return !searchDto.isStopSearch() && searchDto.getQaQueryDto().isShowAll();
    }

    @Override
    protected void doSearchOrDeal(final SearchDto searchDto) throws Exception {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("start searchOperationImplQueryShowAll {}", searchDto);
        }
        try {
            List<EsQuestion> result = null;
            if (querySubjectFormConfig) {
                result = subjectLevelService.queryAll(searchDto.getQaQueryDto());
            }else {
                result = esService.queryAll(searchDto.getQaQueryDto());
            }
            if (CollectionUtils.isNotEmpty(result)) {
                searchDto.setEsQuestions(result);
                searchDto.setStopSearch(true);
            }
        }  catch (Exception e) {
            searchDto.setErrorFlag(true);
            LOGGER.error("SearchOperationImplQueryShowAll error", e);
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("end searchOperationImplQueryShowAll {}", searchDto);
        }
    }

}
